package com.xyy.saas.payment.util.mq;

import com.xyy.saas.payment.adpater.RouteManager;
import com.xyy.saas.payment.api.impl.PaymentOrderApiImpl;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.RocketMqGroup;
import com.xyy.saas.payment.common.RocketMqTopic;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.bo.SeparateAccountsBo;
import com.xyy.saas.payment.cores.bo.UserBo;
import com.xyy.saas.payment.cores.enums.BusinessIdTypeEnum;
import com.xyy.saas.payment.cores.enums.BusinessTypeEnum;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.cores.vo.ResultVO;
import com.xyy.saas.payment.cores.vo.SeparateAccountFromUserVo;
import com.xyy.saas.payment.dao.model.ThirdUserInfo;
import com.xyy.saas.payment.merchant.core.dto.QueryAccountDto;
import com.xyy.saas.payment.payment.core.service.ProfitSharingService;
import com.xyy.saas.payment.service.PayAccountService;
import com.xyy.saas.payment.service.ThirdUserInfoService;
import com.xyy.saas.payment.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Slf4j
@Service
@RocketMQMessageListener(topic = RocketMqTopic.TOPIC_FM_FROZEN_AMOUNT_HANDLE, consumerGroup = RocketMqGroup.TOPIC_FM_FROZEN_AMOUNT_HANDLE_GROUP, consumeMode = ConsumeMode.ORDERLY)
public class FBank2PinganHandlerFrozenAmountConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener  {
    @Resource
    private PayAccountService payAccountService;
    @Resource
    private ThirdUserInfoService thirdUserInfoService;
    @Resource
    private RouteManager routeManager;
    @Resource
    private ProfitSharingService profitSharingService;
    @Resource
    private PaymentOrderApiImpl paymentOrderApi;

    @Override
    public void onMessage(MessageExt message) {
        String accountId = JSONUtils.parse2Object(new String(message.getBody()), String.class);
        log.info("CallbackRechargeHandleConsumer#onMessage accountId:{}",  accountId);

        try {
            ThirdUserInfo thirdUserInfo = thirdUserInfoService.getThirdUserInfoByUserId(accountId);

            if(thirdUserInfo == null) {
                throw new PaymentException(ResultCodeEnum.THIRD_USER_ID_NOT_EXIST);
            }

            UserBo fBankBalance = routeManager.queryAccount(QueryAccountDto.
                    build(thirdUserInfo.getBusinessIdType(), accountId, thirdUserInfo.getThirdUserId()));
            log.info("CallbackRechargeHandleConsumer#onMessage fBankBalance:{}", JSONUtils.toJSON(fBankBalance));

            if(fBankBalance.getFrozenAmount() > NumberUtils.INTEGER_ZERO) {
                String businessId = payAccountService.getBusinessUserIdByAccountId(accountId);

                // 1.冻结余额全部解冻
                profitSharingService.unfrozenBalance(thirdUserInfo.getBusinessIdType(), accountId, fBankBalance.getFrozenAmount().intValue());

                // 2.冻结金额转入平台
                SeparateAccountFromUserVo merchant2platform = new SeparateAccountFromUserVo();
                merchant2platform.setBusinessOrderNo(businessId + "_clear_frozen_amount"); // 商户标识作为转账单号
                merchant2platform.setBusinessType(BusinessTypeEnum.EC.getType());
                merchant2platform.setBusinessIdType(BusinessIdTypeEnum.EC_POP.getType());
                merchant2platform.setBusinessOrderType(BusinessIdTypeEnum.EC_POP.getType());

                merchant2platform.setBusinessUserIdOut(businessId);
                merchant2platform.setBusinessUserIdIn("ec_pop_platform");
                merchant2platform.setAmount(fBankBalance.getFrozenAmount().intValue());

                merchant2platform.setInvoker(StringUtils.EMPTY);
                merchant2platform.setExtra("富民商户冻结余额清空（商户->平台）");
                ResultVO<SeparateAccountsBo> fBankTransfer = paymentOrderApi.separateAccountFromUser(merchant2platform, StringUtils.EMPTY);

                if(!ResultCodeEnum.SUCCESS.getCode().equals(fBankTransfer.getCode())) {
                    throw new PaymentException(fBankTransfer.getDisplayMsg());
                }
            }
        }
        catch(Exception  ex) {
            log.error(ex.getMessage() + ", accountId=" + accountId, ex);
        }
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
    }
}
